//
//  AddressDetailViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/10/18.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import SVProgressHUD
class AddressDetailViewController: BaseViewController {
    
    var cancelBtn :UIButton = UIButton()
    var outerImage:UIImageView = UIImageView()
    var whiteView :UIView = UIView(frame: CGRect(x: 0, y: 90, width: kScreenWidth, height: kScreenHeight))
    //背景区域的颜色和透明度
    var backgroundColor1:UIColor  = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
    var topOrBottomViewStartFrame = CGRect.init(x: 25, y: kScreenHeight, width: kScreenWidth, height: 500)

    override func viewDidLoad() {
        super.viewDidLoad()
        layoutNav()
        makeBaseUI()
        
        
      
        // Do any additional setup after loading the view.
    }
    func layoutNav (){
        self.title = XALanguageManager.getString(key: "钱包")
//        
//        let leftBarBtn = UIBarButtonItem(title: "", style: .plain, target: self,action: #selector(AddressDetailViewController.backToRoot))
//        leftBarBtn.image = UIImage(named: "返回-4444")
//        self.navigationItem.leftBarButtonItem = leftBarBtn;
        
        let rightTitle = XALanguageManager.getString(key: "解除绑定")
        let rightTitleFont = UIFont.systemFont(ofSize: 15);
        let rightTitleSize = NSString(string: rightTitle).size(withAttributes: [NSAttributedStringKey.font:rightTitleFont])
        let rightBtn = UIButton(frame: CGRect(x: 0, y: 0, width: rightTitleSize.width, height: rightTitleSize.height));
        rightBtn .addTarget(self, action: #selector(AddressDetailViewController.relieveAlert(sender:)), for: UIControlEvents.touchUpInside)
        rightBtn.setTitle(rightTitle, for: .normal)
        rightBtn.setTitleColor(UIColor.white, for: .normal)
        rightBtn.titleLabel?.font = rightTitleFont;
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn);
    }
    @objc func relieveAlert(sender:UIButton){
        sender.isUserInteractionEnabled = false
        let alertController = UIAlertController(title: "解除绑定", message: "确定要解除钱包与账号的关联吗？", preferredStyle: .alert);
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (_) in}
        let cance2 = UIAlertAction(title: "确定", style: .default) { (_) in
            self.relieve()
        }
        alertController.addAction(cancel)
        alertController.addAction(cance2)
        self.present(alertController, animated: true) {sender.isUserInteractionEnabled = true}
    }
    @objc func relieve(){
        SVProgressHUD.setDefaultMaskType(.clear)
        SVProgressHUD.show(withStatus: XALanguageManager.getString(key: "正在解除绑定"))
        MyNetwork.request(target: .relieveBindAccount(userId: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            if needModel.code == 1111{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "解除成功"))
                Defaults[.content] = ""
                self.navigationController?.popViewController(animated: true)
            }
            if needModel.code == 0000{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "解除失败"))
            }
            if needModel.code == 0003{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "删除keystore失败"))
            }
            if needModel.code == 0001{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "用户不存在"))
            }
            if needModel.code == 0002{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "用户还没有绑定钱包"))
            }
            if needModel.code == 2222{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "请先登录"))
            }
            SVProgressHUD.dismiss()
        }) { (error) in
            self.navigationController?.view.makeToast(XALanguageManager.getString(key: "解除失败"))
            SVProgressHUD.dismiss();
        }
    }
    
    @objc func backToRoot(){
        self.navigationController?.popViewController(animated: true)
    }
    
    func makeBaseUI(){
        self.view.addSubview(whiteView)
        addWhiteViewSubView()
        
    }
    
    @objc func copyCode() {
        UIPasteboard.general.string = Defaults[.content]
         SVProgressHUD.showSuccess(withStatus: XALanguageManager.getString(key: "复制成功"))
        SVProgressHUD.dismiss(withDelay: 0.5)
        
        
        
    }
    
    func addWhiteViewSubView() {
        
        let imageView: UIImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: whiteView.frame.size.width, height: whiteView.frame.size.height))
        imageView.layer.masksToBounds = true
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        imageView.image = UIImage.init(named: "bmw_image")
        imageView.isUserInteractionEnabled = true
        imageView.backgroundColor = UIColor.clear
        whiteView.addSubview(imageView)
        let titleLabel: UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 15, width: whiteView.frame.size.width, height: 16))
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.text = XALanguageManager.getString(key: "Transfer address")
        titleLabel.textColor = UIColor.white
        titleLabel.textAlignment = .center
        imageView.addSubview(titleLabel)
        
        let topphoto = UIImageView()
        topphoto.layer.cornerRadius = 23;
        imageView.addSubview(topphoto)
        topphoto.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: 64, height: 64))
            make.top.equalTo(60)
        }
        topphoto.sd_setImage(with: NSURL.init(string: "")! as URL, placeholderImage: UIImage.init(named: "THTC币@2x"), options: [], progress: nil, completed:nil)
        
        
        
        let contentLabel: UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 130 , width: whiteView.frame.size.width - 40, height: 16))
        contentLabel.textColor = UIColor("909090")
        contentLabel.font = UIFont.systemFont(ofSize: 15)
        contentLabel.numberOfLines = 0
        contentLabel.textAlignment = NSTextAlignment.center
        contentLabel.text = Defaults[.content]
        contentLabel.adjustsFontSizeToFitWidth = true
        imageView.addSubview(contentLabel)
        
        
        
        let codeImage = UIImageView()
        codeImage.layer.cornerRadius = 23;
        imageView.addSubview(codeImage)
        codeImage.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: 200, height: 200))
            make.top.equalTo(160)
        }
        let url = Defaults[.content] as! String;
        //你的头像（可以为nil）
        let headerImage = UIImage(named: "")
        //生成图片并且显示
        codeImage.image = setupQRCodeImage(url, image: headerImage)
        
        let Bottombutton = UIButton()
        Bottombutton.layer.cornerRadius = 20;
        imageView.addSubview(Bottombutton)
        Bottombutton.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 50, height: 44))
            make.top.equalTo(codeImage.snp.bottom).offset(15)
        }
        Bottombutton.backgroundColor = UIColor("#297EFB")
        Bottombutton.setTitle(XALanguageManager.getString(key: "Copy wallet address"), for: .normal)
        
        Bottombutton.addTarget(self, action: #selector(AddressDetailViewController.copyCode), for: .touchUpInside)
        let bottomLabel = UILabel()
        //        bottomLabel.layer.cornerRadius = 23;
        imageView.addSubview(bottomLabel)
        bottomLabel.font = UIFont.systemFont(ofSize: 13)
        bottomLabel.textAlignment = .center
        bottomLabel.adjustsFontSizeToFitWidth = true
        bottomLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 20, height: 17))
            make.top.equalTo(Bottombutton.snp.bottom).offset(15)
        }
        bottomLabel.text = XALanguageManager.getString(key: "")
        bottomLabel.textColor = UIColor("#297EFB")
        //

        let cancelButton = UIButton(frame: CGRect(x: 15, y: 15, width: 15, height: 15))
        cancelButton.setImage(UIImage.init(named: "关  闭@2x"), for: .normal)
        cancelButton.isHidden = true
        imageView.addSubview(cancelButton)
//        cancelButton.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        
    }
    
   

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 width: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
